<template>
  <div class="container">
    <router-view></router-view>
    <div class="index">
      <Header :isShowMyCourse="true" />
      <div class="main-center2" style="height: auto; margin-bottom: 0px">
        <div class="train-play-main">
          <div class="pl-list">
            <div class="t-tit">
              <label class="fanhui fl" @click="goBack()">
                <img src="static/img/s_back2.png" />
                返回
              </label>
              <span class="bt">{{ course.name }}</span>
            </div>

            <div class="clear"></div>
            <div class="play-area fl" id="video" ref="video" v-if="getFileType(palyFile)=='video'"></div>
            <div class="play-area fl" v-else-if="getFileType(palyFile)=='radio'">
              <div class="item-play" :style="{ 'background-image': 'url(' + bgImg + ')' }">
                <img v-if="showImg" :class="isPlayMusic ? activeClass : errorClass" src="../../../static/img/music1.png" style="width: 372px;min-height: 372px;" />
                <div class="item-read" v-else>
                  <div
                    v-for="(item, index) in read"
                    :key="index"
                    class="item-all"
                  >
                    <span v-if="index + 1 < read.length">
                      <span :class="[currentTxt > read[index].time - 1 && currentTxt < read[index + 1].time ? 'item-color' : '']">{{ item.text }}</span>
                    </span>
                  </div>
                </div>
                <div class="">
                  <audio @ended="stopMusic()" @pause="stopMusic()" @play="playMusic()" id="audio" class="" @timeupdate="update" :src="music" controls="controls" controlsList="nodownload">
                    Your browser does not support the audio element.
                  </audio>
                </div>
              </div>
            </div>
            <ul
              class="play-list fr"
              style="height: 648px; overflow-y: auto; width: 255px; padding: 0"
            >
              <li v-for="(item, index) in list">
                <span
                  @click="
                    aliplay(
                      'video',
                      item.file,
                      index,
                      course.onlinestatus,
                      item
                    )
                  "
                  :class="{ cur: index == current }"
                  class="class-title-view"
                >
                  <label>{{ item.name }}</label>
                  <img
                    class="pic fr"
                    v-if="item.type == 'file'"
                    src="../../../static/img/zj1-v3.png"
                  />
                  <img v-else src="static/img/play-v.png" class="pic fr" />
                </span>
                <div
                  class="gonect class-title-view"
                  style="font-size: 12px; height: 50px"
                  v-for="(items, indexs) in item.content_topic"
                  @click="goNext(item.id, items.key, 1, items.value)"
                >
                  <label>{{ items.name }}</label>
                  <img
                    class="pic fr"
                    v-if="items.type == 'file'"
                    src="../../../static/img/zj1-v3.png"
                  />
                  <img
                    v-else
                    src="../../../static/img/zj1-v2.png"
                    class="pic fr"
                  />
                </div>
              </li>
            </ul>
          </div>
        </div>

        <div class="r-xcx"><span class="sp">微信小程序</span>
          <div class="r-xcx2">
            <h3>培训平台小程序</h3>
        <img width="169" style="margin-top: 26px;" src="/static/img/qr.png" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
var player;
import Header from '../../components/header_train.vue';
import Copyright from '../../components/copyright2.vue';
export default {
  data() {
    return {
      isOpen: true,
      value: [],
      id: '',
      course: '',//课程信息
      info: '',
      classid: '',
      list: '',
      video: [],
      source: '',
      current: 0,
      token: localStorage.getItem('token'),
      palyFile: '',
      currentZiyuan: {},
      currentTxt: 0, //当前歌词所在位置
      array: [], //全部歌词
      indexArray: 0, //监听高亮歌词显示
      read: [], //截取的要显示的歌词
      showImg: true, //没有歌词显示转动图片，
      bgImg: '../../../static/img/music-bg.jpg', //轮播背景图
      bgTimer: '',
      bgAllImg: ['../../../static/img/music-bg.jpg'], //当前播放歌曲轮播的背景图片
      flag: 0, //防止定时器多次执行
      imgNum: 0, //轮播图第几张
      music: '',
      isPlayMusic: false,
      activeClass: 'playM',
      errorClass: 'stopM',
    };
  },
  created() {
    this.id = this.$route.query.id;
    this.classid = this.$route.query.classid;
    this.getInfo();
  },
  beforeDestroy() {
    console.log('before');
    this.getplaytime(this.current, localStorage.getItem(this.source));
  },

  watch: {
    //监听时间变化
    currentTxt(newv) {
      if (newv > 1) {
        var ret = this.array.findIndex((value, index, arr) => {
          return value.time == newv;
        });
        if (ret != -1) {
          this.indexArray = ret;
        }
        this.read = this.array.slice(this.indexArray - 1, this.indexArray + 10);
      }
    }
  },
  methods: {
    getFileType(fileName) {
      // 后缀获取
      let suffix = '';
      // 获取类型结果
      let result = '';
      try {
        const flieArr = fileName.split('.');
        suffix = flieArr[flieArr.length - 1];
      } catch (err) {
        suffix = '';
      }
      // fileName无后缀返回 false
      if (!suffix) {
        return false;
      }
      suffix = suffix.toLocaleLowerCase();
      // 图片格式
      const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
      // 进行图片匹配
      result = imglist.find(item => item === suffix);
      if (result) {
        return 'image';
      }
      // 匹配txt
      const txtlist = ['txt'];
      result = txtlist.find(item => item === suffix);
      if (result) {
        return 'txt';
      }
      // 匹配 excel
      const excelist = ['xls', 'xlsx'];
      result = excelist.find(item => item === suffix);
      if (result) {
        return 'excel';
      }
      // 匹配 word
      const wordlist = ['doc', 'docx'];
      result = wordlist.find(item => item === suffix);
      if (result) {
        return 'word';
      }
      // 匹配 pdf
      const pdflist = ['pdf'];
      result = pdflist.find(item => item === suffix);
      if (result) {
        return 'pdf';
      }
      // 匹配 ppt
      const pptlist = ['ppt', 'pptx'];
      result = pptlist.find(item => item === suffix);
      if (result) {
        return 'ppt';
      }
      // 匹配 视频
      const videolist = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
      result = videolist.find(item => item === suffix);
      if (result) {
        return 'video';
      }
      // 匹配 音频
      const radiolist = ['mp3', 'wav', 'wmv'];
      result = radiolist.find(item => item === suffix);
      if (result) {
        return 'radio';
      }
      // 匹配 swf
      const swflist = ['swf'];
      result = swflist.find(item => item === suffix);
      if (result) {
        return 'swf';
      }
      //匹配html
      const htmllist = ['html'];
      result = htmllist.find(item => item === suffix);
      if (result) {
        return 'html';
      }
      // 其他 文件类型
      return 'other';
      console.log(fileName);
    },
    getplaytime(current, overtime) {
      var content_id;
      this.list.forEach((item, index) => {
        if (index == current) {
          content_id = item.id;
        }
      });
      if (overtime != null) {
        this.$api('getCourseList.getplaytime', {
          token: this.token,
          content_id: content_id,
          overtime: parseInt(overtime)
        }).then(res => { });
        this.$api('getCourseList.updateStudy', {
          token: this.token,
          course_id: this.id,
          content_id: content_id,
          overtime: parseInt(overtime)
        }).then(res => { });
      }
    },
    //获取当前音频播放时间
    update() {
      var audio = document.querySelector('audio');
      if (audio != null) {
        this.currentTxt = parseInt(audio.currentTime);
      }
    },
    playMusic() {
      this.isPlayMusic = true;
      console.log('playMusic');
      //背景开始轮播
      clearInterval(this.bgTimer);
      this.playBg();
    },
    stopMusic() {
      console.log('stopMusic');
      //背景停止轮播
      clearInterval(this.bgTimer);
      this.isPlayMusic = false;
    },


    //content_id章节id
    async aliplay(id, source, index, setting, item) {
      this.currentZiyuan = item;
    },
    playBg() {
      if (this.bgAllImg.length > 1) {
        this.bgTimer = setInterval(() => {
          this.flag = 1;
          this.bgImg = this.bgAllImg[this.imgNum];
          if (this.imgNum == this.bgAllImg.length - 1) {
            this.imgNum = -1;
          }
          this.imgNum++;
        }, this.currentZiyuan.rotation_times || 10000);
      } else {
        clearInterval(this.bgTimer);
      }
    },

    //content_id章节id
    async aliplay(id, source, index, setting, item) {
      this.currentZiyuan = item;

      var that = this;
      this.current = index
      clearInterval(this.bgTimer);
      this.bgTimer = null;
      this.flag = 0;
      this.imgNum = 1;
      this.isPlayMusic = false;
      this.palyFile = item.file
      if (this.getFileType(item.file) == 'radio') {
        console.log("music")
        this.music = item.file
        // //是否有歌词，有歌词进行处理
        if (item.lyric_text != '' && item.lyric_text != undefined) {
          this.array = [];
          this.showImg = false;
          let lyricArr = item.lyric_text.split('[').slice(1); // 先以[进行分割
          let lrcObj = {};
          lyricArr.forEach(item => {
            var data = {};
            let arr = item.split(']'); // 再分割右括号
            // 时间换算成秒
            let m = parseInt(arr[0].split(':')[0]);
            let s = parseInt(arr[0].split(':')[1]);
            arr[0] = m * 60 + s;
            data.time = arr[0];
            if (arr[1] != '\n') {
              // 去除歌词中的换行符
              lrcObj[arr[0]] = arr[1];
              data.text = arr[1];
            }
            this.array.push(data);
          });

          this.read = this.array.slice(0, this.indexArray + 10);
          console.log("this.read：" + this.read);
        } else {
          this.showImg = true;
        }
        if (item.rotation_img_text != '' && item.rotation_img_text != undefined) {
          this.showImg = false
          console.log(item.rotation_img_text);
          this.bgAllImg = item.rotation_img_text;
          this.bgImg = this.bgAllImg[0];
          this.showImg = false;
        } else {
          this.bgImg = '../../../static/img/music-bg.jpg';
          this.bgAllImg = [];
          clearInterval(this.bgTimer);
          this.flag = 0;
        }
        if (this.flag == 1) {
          return;
        }
        //播放背景
        this.playBg();
        return;
      }
      var watch = {};
      await this.$api('index.getplayInfo', {
        token: this.token,
        content_id: item.id
      }).then(res => {
        watch.FD = res.data.FD;
        watch.LD = res.data.LD;
        watch.SD = res.data.SD;
      });
      this.$api('getCourseList.checkstudyorder', {
        token: this.token,
        course_id: this.id,
        content_id: item.id
      }).then(res => {
        if (res.data.status == 0) {
          this.$message({
            message: '请按顺序播放视频',
            type: 'info'
          });
          return;
        } else {

          var overtime = localStorage.getItem(this.source);
          this.getplaytime(this.current, overtime);
          this.source = source;
          this.current = index;
          if (player) {
            player.dispose();
          }
          const saveTime = function (memoryVideo, currentTime) {
            localStorage.setItem(memoryVideo, currentTime);
          };
          const getTime = function (memoryVideo) {
            //return返回的是自定义起播时间
            return localStorage.getItem(memoryVideo);
          };

          if (setting == 1) {

            this.$nextTick(() => {
              player = new Aliplayer({
                id: id,
                source: JSON.stringify(watch),
                width: '82%',
                height: '700px',
                autoplay: false,
                isLive: false,
                components: [{
                  name: 'MemoryPlayComponent',
                  type: AliPlayerComponent.MemoryPlayComponent,
                  args: [false, getTime, saveTime]
                },
                {
                  name: 'QualityComponent',
                  type: AliPlayerComponent.QualityComponent
                },

                {
                  name: 'RateComponent',
                  type: AliPlayerComponent.RateComponent
                }

                ],
                skinLayout: [{
                  name: 'controlBar',
                  align: 'blabs',
                  x: 0,
                  y: 0,
                  children: [{
                    name: 'progress',
                    align: 'blabs',
                    x: 0,
                    y: 44
                  },
                  {
                    name: 'playButton',
                    align: 'tl',
                    x: 15,
                    y: 12
                  },
                  {
                    name: 'timeDisplay',
                    align: 'tl',
                    x: 10,
                    y: 7
                  },
                  {
                    name: 'fullScreenButton',
                    align: 'tr',
                    x: 10,
                    y: 12
                  },
                  {
                    name: 'volume',
                    align: 'tr',
                    x: 5,
                    y: 10
                  }
                  ]
                }]
              },
                function (player) {
                  console.log(localStorage.getItem(source));
                  console.log('The player is created');
                  player.on('timeupdate', function (e) {
                    localStorage.setItem(source, player.getCurrentTime());
                  });
                  player.on('pause', function (e) {
                    console.log('zamnt');
                  });
                  player.on('ended', function (e) {
                    console.log('播放完成');
                    that.getplaytime(that.current, localStorage.getItem(that.source));
                  });
                  var memory_time = localStorage.getItem(source);
                  if (memory_time) {
                    player.seek(memory_time);
                  }
                }
              );
            });

          } else {
            this.$nextTick(() => {
              player = new Aliplayer({
                id: id,
                source: JSON.stringify(watch),
                width: '82%',
                height: '700px',
                autoplay: false,
                isLive: false,
                components: [{
                  name: 'MemoryPlayComponent',
                  type: AliPlayerComponent.MemoryPlayComponent,
                  args: [false, getTime, saveTime]
                },
                {
                  name: 'QualityComponent',
                  type: AliPlayerComponent.QualityComponent
                }
                ],
                skinLayout: [{
                  name: 'controlBar',
                  align: 'blabs',
                  x: 0,
                  y: 0,
                  children: [

                    {
                      name: 'playButton',
                      align: 'tl',
                      x: 15,
                      y: 12
                    },
                    {
                      name: 'timeDisplay',
                      align: 'tl',
                      x: 10,
                      y: 7
                    },
                    {
                      name: 'fullScreenButton',
                      align: 'tr',
                      x: 10,
                      y: 12
                    },
                    {
                      name: 'volume',
                      align: 'tr',
                      x: 5,
                      y: 10
                    }
                  ]
                }]
              },
                function (player) {
                  console.log(localStorage.getItem(source));
                  console.log('The player is created');
                  player.on('timeupdate', function (e) {
                    localStorage.setItem(source, player.getCurrentTime());
                  });
                  player.on('pause', function (e) {
                    console.log('zamnt');
                  });
                  player.on('ended', function (e) {
                    console.log('播放完成');
                    that.getplaytime(that.current, localStorage.getItem(that.source));
                  });
                  var memory_time = localStorage.getItem(source);
                  if (memory_time) {
                    player.seek(memory_time);
                  }
                }
              );
            });

          }

        }
      });
    },

    getInfo() {
      this.$api("getCourseList.getUserStudyInfo", {
        token: this.token,
        course_id: this.id,
      }).then((res) => {
        this.course = res.data.course;
        this.list = res.data.list;
        if (this.classid == "undefined") {
          res.data.list[0].isOpen = true;
          this.current = 0;
          this.video.push(res.data.list[0].file);
          this.aliplay(
            "video",
            this.video[0],
            this.current,
            this.course.onlinestatus,
            res.data.list[0]
          );
        } else {
          res.data.list.forEach((item, index) => {
            if (item.id == this.classid) {
              this.info = item;
              item.isOpen = true;
              this.current = index;
              this.video.push(item.file);
              this.aliplay(
                "video",
                this.video[0],
                this.current,
                this.course.onlinestatus,
                item
              );
            }
          });
        }
      });
    },
    //打开附件
    goNext(id, key, type, value) {
      if (this.course.overduestatus == 1) {
        this.$message({
          message: '课程已过期，无法查看',
          type: 'info'
        });
        return;
      }
      if (this.course.paystatus == 0) {
        this.$message({
          message: '请先报名',
          type: 'success'
        });
      }
      if (this.course.downstatus == 0) {
        let routerUrl = this.$router.resolve({
          path: '/classPlay',
          query: {
            id: id,
            key: key,
            type: type
          }
        });
        window.open(routerUrl.href, '_blank')
      } else if (this.course.downstatus == 1) {
        window.open(value);
      }

    },
    goBack() {
      this.$router.go(-1);
    },
    goCollect() {
      this.$router.push("/courseCollect");
    },
  },
  components: {
    Header,
    Copyright,
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-input__inner {
  height: 36px;
  line-height: 35px;
  outline: 0;
}

.cur {
  background-color: rgba(0, 0, 0, 0.16);
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.stopM {
  animation: rotate 3s linear infinite;
  animation-play-state: paused;
}

.playM {
  animation: rotate 3s linear infinite;
  animation-play-state: running;
}

.item-zan {
  img {
    width: 66px;
    height: 66px;
  }
}

.item-bg {
  background-image: no-repeat;
  background-size: cover;
}

.item-read {
}

.item-all {
  padding: 15px;
  font-size: 18px;
}

.item-color {
  color: #fff;
  font-size: 22px;
}

.class-title-view {
  display: flex !important;
  align-items: center !important;
  justify-content: space-between !important;
  padding: 0 5px 0 10px;
  .pic {
    margin-top: 0 !important;
  }
}

.play-list {
  width: 18%;
  padding: 0;
  li .cur {
    padding: 0 5px;
    box-sizing: border-box;
  }
}
</style>
